package cn.school.demo.ui.login

import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import cn.school.demo.R
import cn.school.demo.databinding.FragmentLoginBinding
import cn.school.demo.MyApplication
import cn.school.demo.pojo.User
import cn.school.demo.util.StringUtil
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog
import java.lang.Error

/**
 * 界面： 登录界面
 * 说明： 免登录
 */
class LoginFragment : Fragment() {

    private lateinit var viewModel: LoginViewModel
    private lateinit var binding: FragmentLoginBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false)
        binding.loginProgressBar.visibility = View.INVISIBLE
        binding.vm = viewModel
        binding.lf = this
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        binding.loginProgressBar.visibility = View.INVISIBLE
        MyApplication.animationCountdown["Login"]?.let {
            MyApplication.animationCountdown(
                binding.getSecurityCodeButton,
                MyApplication.animationCountdown["Login"],
                "Login"
            )
        }
    }

    fun updateId() = viewModel.setId(binding.accountTextView.text.toString())

    fun updatePwd() = viewModel.setPwd(binding.passwordLoginTextView.text.toString())

    fun updatePhone() = viewModel.setPhone(binding.phoneTextView.text.toString())

    fun updateCode() = viewModel.setCode(binding.securityCodeTextView.text.toString())

    fun accountPasswordLoginButtonOnClick() {
        viewModel.changeView(false)
        viewModel.setId("")
        viewModel.setPwd("")
        binding.AccountPasswordLoginButton.visibility = View.GONE
        binding.PhoneLoginButton.visibility = View.VISIBLE
    }

    fun phoneLoginButtonOnClick() {
        viewModel.changeView(true)
        viewModel.setPhone("")
        viewModel.setCode("")
        binding.PhoneLoginButton.visibility = View.GONE
        binding.AccountPasswordLoginButton.visibility = View.VISIBLE
    }

    fun loginButtonOnClick() {
        val id = viewModel.id.value.toString()
        val pwd = viewModel.pwd.value.toString()
        val toastText =
            if (id.isEmpty()) "学（工）号不能为空！"
            else if (pwd.isEmpty()) "密码不能为空！"
            else if (!StringUtil.isStudentID(id)) "学（工）号输入不合法！"
            else if (!StringUtil.isPassword(pwd)) "密码输入不合法!"
            else null
        toastText?.let {
            //ToastUtils.showShort(toastText)
            CircleDialog.Builder().setText(toastText).setTextColor(Color.RED)
                .setNegative("确定", null).show(parentFragmentManager)
        } ?: let {
            binding.loginProgressBar.visibility = View.VISIBLE
            //获取账号密码，调用http请求，发往后端，判断是否正确
            viewModel.getUser(id.toInt(), pwd)
            viewModel.new.observe(viewLifecycleOwner) {
                binding.loginProgressBar.visibility = View.INVISIBLE
                if (it != null) {
                    when (it.success) {
                        true -> {
                            try {
                                it.data["user"]?.let { jsonData ->
                                    val user = GsonUtils.fromJson<User>(
                                        jsonData.toString(),
                                        object : TypeToken<User>() {}.type
                                    )
                                    MyApplication.user = user
                                    MyApplication.goto(
                                        R.id.action_Login_to_Article,
                                        findNavController(),
                                        parentFragmentManager
                                    )
                                    LogUtils.d(
                                        it,
                                        "账号密码登录验证成功！",
                                        "获取此账号个人信息成功！",
                                        MyApplication.user
                                    )
                                } ?: let {
                                    LogUtils.e("账号密码登录的http返回值的data怎么没有user呢？？")
                                    CircleDialog.Builder().setText("网络错误，请检查网路重试！")
                                        .setTextColor(Color.RED)
                                        .setNegative("确定", null)
                                        .show(parentFragmentManager)
                                }
                            } catch (e: Error) {
                                e.printStackTrace()
                            }
                        }
                        false -> {
                            CircleDialog.Builder().setText(it.message).setTextColor(Color.RED)
                                .setNegative("确定", null)
                                .show(parentFragmentManager)
                        }
                    }
                } else {
                    CircleDialog.Builder().setText("无此用户！").setTextColor(Color.RED)
                        .setNegative("确定", null)
                        .show(parentFragmentManager)
                }
            }
        }
    }

    fun getSecurityCodeButtonOnClick() {
        val phone = viewModel.phone.value.toString()
        val code = viewModel.code.value.toString()
        LogUtils.d(phone, code)
        val toastText = if (phone.isEmpty()) "手机号不能为空！"
        else if (!StringUtil.isMobilePhone(phone)) "手机号不合法！"
        else null
        toastText?.let { //ToastUtils.showShort(toastText)
            CircleDialog.Builder().setText(toastText).setTextColor(Color.RED)
                .setNegative("确定", null).show(parentFragmentManager)
        } ?: let {
            MyApplication.animationCountdown(binding.getSecurityCodeButton, null, "Login")
            viewModel.getCodeText(binding.phoneTextView.text.toString())
            viewModel.getCode.observe(viewLifecycleOwner) {
                ToastUtils.showShort("发送短信成功！请耐心等待！")
            }
        }
    }

    fun loginButton2OnClick() {
        val phone = viewModel.phone.value.toString()
        val code = viewModel.code.value.toString()
        LogUtils.d(phone, code)
        val toastText = if (phone.isEmpty()) "手机号不能为空！"
        else if (!StringUtil.isMobilePhone(phone)) "手机号不合法！"
        else if (code.isEmpty()) "验证码不能为空！"
        else null
        toastText?.let { //ToastUtils.showShort(toastText)
            CircleDialog.Builder().setText(toastText).setTextColor(Color.RED)
                .setNegative("确定", null).show(parentFragmentManager)
        } ?: let {
            if (code == viewModel.getCode.value) {
                binding.loginProgressBar.visibility = View.VISIBLE
                viewModel.getResult(phone)
                viewModel.result.observe(viewLifecycleOwner) {
                    binding.loginProgressBar.visibility = View.INVISIBLE
                    when (it.success) {
                        true -> {
                            try {
                                it.data["user"]?.let { jsonData ->
                                    val user = GsonUtils.fromJson<User>(
                                        jsonData.toString(),
                                        object : TypeToken<User>() {}.type
                                    )
                                    MyApplication.user = user
                                    LogUtils.d(MyApplication.user)
                                    MyApplication.goto(
                                        R.id.action_Login_to_Article,
                                        findNavController(),
                                        parentFragmentManager
                                    )
                                } ?: let {
                                    CircleDialog.Builder().setText("数据错误，请重新登录！")
                                        .setTextColor(Color.RED).setNegative("确定", null)
                                        .show(parentFragmentManager)
                                }
                            } catch (e: Error) {
                                LogUtils.e(e.printStackTrace())
                            }
                        }
                        false -> {
                            CircleDialog.Builder().setText(it.message + "是否前往注册？")
                                .setTextColor(Color.RED)
                                .setPositive("确定") {
                                    findNavController().navigate(R.id.action_Login_to_register)
                                }.setNegative("取消", null).show(parentFragmentManager)
                        }
                    }
                }
            } else {
                CircleDialog.Builder().setText("验证码错误！").setNegative("确定") {
                    viewModel.setCode("")
                }.show(parentFragmentManager)
            }
        }
    }

    fun registeredButtonOnClick() = findNavController().navigate(R.id.action_Login_to_register)

    fun registeredForgetPSWInButtonOnClick() =
        findNavController().navigate(R.id.action_Login_to_forget_pwd_first)
}